// pages/group-list/group-list.ts
import { getPublishList } from '../../../api/publish';
import { PAGES, goToPage } from '../../../config/pages';
import { formatDate } from '../../../utils/time';
import { formatSpecification } from '../../../utils/util';
import util from '../../../utils/util';
import { getCategoryNames, getProductsByCategory } from '../../../config/product-categories';

Page({
  data: {
    groups: [] as any[],
    loading: false,
    page: 1,
    limit: 20,
    hasMore: true,
    // 筛选条件
    selectedProvince: '',
    selectedCity: '',
    selectedDistrict: '',
    filterActive: false,
    // 搜索关键词
    keyword: '',
    // 城市筛选弹窗
    showCityFilter: false,
    cityFilterValue: null as any,
    // 分类筛选
    selectedProductCategory: '', // 产品类别
    selectedProductName: '', // 产品名称
    selectedCategoryText: '', // 显示的分类文本
    // 临时选择状态（用于弹窗中的选择）
    tempSelectedProductCategory: '', // 临时产品类别选择
    tempSelectedProductName: '', // 临时产品名称选择
    // 分类筛选弹窗
    showCategoryModalFlag: false,
    currentCategoryLevel: 'category', // category, product
    currentCategoryList: [] as string[],
    // 产品类别数据
    productCategoryList: getCategoryNames(), // 产品类别列表
    productNameList: [] as string[], // 产品名称列表（根据选择的产品类别动态加载）
  },

  onLoad() {
    this.loadGroups();
  },

  // 加载拼单列表
  async loadGroups(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        groups: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        type: 'group',
        page: this.data.page,
        limit: this.data.limit
      };

      // 添加筛选条件
      if (this.data.selectedProvince) {
        params.province = this.data.selectedProvince;
      }
      if (this.data.selectedCity) {
        params.city = this.data.selectedCity;
      }
      if (this.data.selectedDistrict) {
        params.district = this.data.selectedDistrict;
      }
      // 添加分类筛选
      if (this.data.selectedProductCategory) {
        params.product_category = this.data.selectedProductCategory;
      }
      if (this.data.selectedProductName) {
        params.product_name = this.data.selectedProductName;
      }
      // 添加搜索关键词
      if (this.data.keyword) {
        params.keyword = this.data.keyword;
      }

      const res = await getPublishList(params);
      
      if (res.status === 200 && res.data) {
        // 格式化日期和规格
        const formattedList = res.data.list.map((item: any) => ({
          ...item,
          spec: formatSpecification(item.spec || ''),
          formatted_date: formatDate(item.add_time || item.create_time),
          participants_display: this.formatParticipants(item.participants || [])
        }));
        
        const newGroups = refresh ? formattedList : [...this.data.groups, ...formattedList];
        
        this.setData({
          groups: newGroups,
          hasMore: newGroups.length < res.data.count,
          page: this.data.page + 1
        });
      }
    } catch (error: any) {
      console.error('加载拼单列表失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加载失败'),
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadGroups(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadGroups();
    }
  },

  // 筛选全国
  filterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false
    });
    this.loadGroups(true);
  },

  // 显示城市选择弹窗
  showCityModal() {
    this.setData({
      showCityFilter: true,
      cityFilterValue: {
        province: this.data.selectedProvince,
        city: this.data.selectedCity,
        district: this.data.selectedDistrict
      }
    });
  },

  // 城市筛选确认
  onCityFilterConfirm(e: any) {
    const { address } = e.detail;
    console.log('选择的城市:', address);
    
    this.setData({
      selectedProvince: address.province || '',
      selectedCity: address.city || '',
      selectedDistrict: address.district || '',
      filterActive: true,
      showCityFilter: false
    });
    
    this.loadGroups(true);
  },

  // 城市筛选取消
  onCityFilterCancel() {
    this.setData({
      showCityFilter: false
    });
  },

  // 清除城市筛选
  onCityFilterClear() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadGroups(true);
  },

  // 选择全国
  onCityFilterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadGroups(true);
  },

  // 跳转到拼单详情
  goToDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    goToPage(PAGES.GROUP_DETAIL, { id });
  },

  // 搜索
  onSearch(e: any) {
    const keyword = e.detail.value;
    console.log('搜索关键词:', keyword);
    this.setData({
      keyword: keyword.trim()
    });
    this.loadGroups(true);
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      keyword: ''
    });
    this.loadGroups(true);
  },

  // 格式化参与者信息
  formatParticipants(participants: any[]) {
    const total = participants.length;
    const displayAvatars = participants.slice(0, 4).map((p: any) => {
      // 获取用户名称（优先使用real_name，其次nickname）
      const name = p.user?.real_name || p.user?.nickname || '匿';
      // 取第一个字
      const firstChar = name.charAt(0);
      return {
        name: firstChar,
        uid: p.uid
      };
    });

    return {
      avatars: displayAvatars,
      hasMore: total > 4,
      total: total
    };
  },

  // 显示分类筛选弹窗
  showCategoryModal() {
    this.setData({
      showCategoryModalFlag: true,
      currentCategoryLevel: 'category',
      // 初始化临时选择状态为当前已选择的值
      tempSelectedProductCategory: this.data.selectedProductCategory,
      tempSelectedProductName: this.data.selectedProductName
    });
    this.loadCategoryList();
  },

  // 隐藏分类筛选弹窗
  hideCategoryModal() {
    this.setData({
      showCategoryModalFlag: false
    });
  },

  // 生成分类显示文本
  generateCategoryText(category: string, product: string) {
    const parts = [];
    if (category) parts.push(category);
    if (product) parts.push(product);
    return parts.join('-');
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 切换分类级别
  switchCategoryLevel(e: any) {
    const level = e.currentTarget.dataset.level;
    this.setData({
      currentCategoryLevel: level
    });
    this.loadCategoryList();
  },

  // 加载分类列表
  loadCategoryList() {
    const { currentCategoryLevel, tempSelectedProductCategory } = this.data;
    let categoryList: string[] = [];

    if (currentCategoryLevel === 'category') {
      // 产品类别
      categoryList = this.data.productCategoryList;
    } else if (currentCategoryLevel === 'product' && tempSelectedProductCategory) {
      // 产品名称（根据产品类别获取）
      categoryList = getProductsByCategory(tempSelectedProductCategory);
    }

    this.setData({
      currentCategoryList: categoryList
    });
  },

  // 选择分类
  selectCategory(e: any) {
    const category = e.currentTarget.dataset.category;
    const { currentCategoryLevel } = this.data;

    if (currentCategoryLevel === 'category') {
      // 选择产品类别
      this.setData({
        tempSelectedProductCategory: category,
        tempSelectedProductName: ''
      });
      this.switchCategoryLevel({ currentTarget: { dataset: { level: 'product' } } });
    } else if (currentCategoryLevel === 'product') {
      // 选择产品名称
      this.setData({
        tempSelectedProductName: category
      });
    }
  },

  // 清除分类筛选
  clearCategoryFilter() {
    this.setData({
      selectedProductCategory: '',
      selectedProductName: '',
      selectedCategoryText: '',
      tempSelectedProductCategory: '',
      tempSelectedProductName: '',
      currentCategoryLevel: 'category'
    });
    this.loadCategoryList();
  },

  // 应用分类筛选
  applyCategoryFilter() {
    const { tempSelectedProductCategory, tempSelectedProductName } = this.data;
    
    // 生成显示文本
    const categoryText = this.generateCategoryText(tempSelectedProductCategory, tempSelectedProductName);
    
    this.setData({
      selectedProductCategory: tempSelectedProductCategory,
      selectedProductName: tempSelectedProductName,
      selectedCategoryText: categoryText
    });
    
    this.loadGroups(true);
    this.hideCategoryModal();
    console.log('按分类筛选:', tempSelectedProductCategory, tempSelectedProductName);
  },

  // Banner链接点击事件
  onBannerLinkTap(e: any) {
    const { linkUrl } = e.detail;
    console.log('Banner链接点击:', linkUrl);
    util.navigateToAdLink(linkUrl);
  }
});

